/**
 * 出牌表现管理类
 */
var ClientDelegate = require('./../../FrameWork/Delegate/ClientDelegate');
var ClientPkDelegateType = require('./../Delegate/ClientPkDelegateType');
var _ = require('./../../FrameWork/we_underscore');
var PkSound = require('./../PkSound');
var EumPkGroup = require('./../Enum/EumPkGroup');
var UtilGameObject = require('./../../FrameWork/Utils/UtilGameObject');
var FindCardGroupType = require('./../FindTool/FindCardGroupType');
var PkCardTool = require('./../FindTool/PkCardTool');
cc.Class({
    extends: ClientDelegate,
    properties: {
        prefabShowOutCard: {
            default: null,
            type: cc.Prefab,
            displayName: '出牌表现单个牌',
        },

        prefabCardTypeAnim: {
            default: null,
            type: cc.Prefab,
            displayName: '牌组特效预设',
        },
        prefabSprite: {
            default: null,
            type: cc.Prefab,
            displayName: '图片预设',
        },
        prefabFeiJi: {
            default: null,
            type: cc.Prefab,
            displayName: '飞机',
        },
        posHeadList: [cc.Node],

        posOutEnd: [cc.Node], //出牌目的地

        spriteAtlasPkType: {
            default: null,
            type: cc.SpriteAtlas,
            displayName: '图集合'
        },
        spriteAtlasBomb: {
            default: null,
            type: cc.SpriteAtlas,
            displayName: '炸弹图集合'
        },
        spriteAtlasBastCardEffect: {
            default: null,
            type: cc.SpriteAtlas,
            displayName: '最大牌特效图集合'
        },
        nodeScene: {
            default: null,
            type: cc.Node,
            displayName: '场景节点'
        },
        nodeBg: {
            default: null,
            type: cc.Node,
            displayName: '背景'
        },

    },

    onLoad() {
        this.addListerDelegate(ClientPkDelegateType.Client_outSelfCtr, this.actOutCtrList.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Client_showOutSelfCtr, this.playCardAnim.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Client_otherOut, this.actOtherOutCard.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Client_clearOutCardAll, this.cleanOutCardAll.bind(this));
        this.addListerDelegate(ClientPkDelegateType.Client_showHandsCardBySeatIdx, this.doShowHandsCard.bind(this));
        this.resetNet();
        this.initTest();
    },
    resetNet() {
        this.outCardAll = [];
    },
    testCreateCards() {
        var _ = require('./../../FrameWork/we_underscore')
            /**生成一幅牌 */
        var allCards = [];
        for (var cardId = 1; cardId <= 52; ++cardId) {
            allCards.push(cardId);
        }
        /**************************************************/
        var randCards = [];
        for (var randNum = 1; randNum <= _.random(10, 18); ++randNum) {
            var maxNum = _.size(allCards);
            var idx = _.random(0, maxNum - 1);
            var randCardId = allCards[idx];
            // var cardInfo = PlanApi.PlanPkConfig.findById(randCardId);
            randCards.push(randCardId);
            allCards = _.without(allCards, randCardId);
        }
        return randCards;
    },
    initTest() {
        UtilGameObject.createDemoBtn([
            // ['出牌1', function() {
            //     this.doShowHandsCard({
            //         seatIdx: 1,
            //         handCards: this.testCreateCards()
            //     });
            // }.bind(this)],
            // ['出牌2', function() {
            //     this.doShowHandsCard({
            //         seatIdx: 2,
            //         handCards: this.testCreateCards()
            //     });
            // }.bind(this)],

            // ['ch', function() {
            //     var info = {
            //         seatIdx: 1,
            //         type: EumPkGroup.STRAIGHT,
            //         cardIds: [_.random(1, 54)]
            //     };
            //     // this.playTypeAnim(info);

            //     // this.playBombAnim(info);


            //     this.actOtherOutCard(info);
            // }.bind(this)],


            // ['顺子', function() {
            //     var info = {
            //         seatIdx: 2,
            //         type: EumPkGroup.STRAIGHT,
            //         cardIds: []
            //     };
            //     for (var i = 0; i < _.random(5, 10); ++i) {
            //         info.cardIds.push(_.random(1, 54));
            //     }
            //     this.actOtherOutCard(info);
            // }.bind(this)],
        ]);
    },
    getOtherD(_seatIdx) {
        var d = _seatIdx == 1 ? 1 : -1;
        return d
    },
    getOtherOutPosX(_seatIdx, _nodeFather, _idx) {
        var sizeFather = _nodeFather.getContentSize();
        var cardSize = this._getPrefabSize();
        var d = this.getOtherD(_seatIdx);
        var fristX = sizeFather.width * 0.5 * d - d * cardSize.width * 0.5 - d * _idx * this.getScapeX();
        return fristX;
    },

    getOutActTime() {
        return 0.5;
    },
    /***将已经打出的牌管理起来 */
    addOutCardAll(_currOutCardCtrList) {
        if (null == this.outCardAll) {
            this.outCardAll = [];
        }
        if (!!_currOutCardCtrList) {
            _.each(_currOutCardCtrList, function(_ctr) {
                this.outCardAll.push(_ctr)
            }.bind(this));
        }
    },
    /**清除所有已出的牌*/
    cleanOutCardAll() {
        if (!!this.outCardAll) {
            if (_.size(this.outCardAll) > 0) {
                _.each(this.outCardAll, function(_ctr) {
                    if (!!_ctr && !!_ctr.getCardInfo && !!_ctr.node) {
                        _ctr.node.destroy();
                    }
                }.bind(this));
            }
        }
        this.outCardAll = [];
    },
    /**亮出手牌 
     * _info:{
     * seatIdx:1
     * handCards:[]
     * }
     */
    doShowHandsCard(_info) {
        if (null == _info.handCards) {
            return;
        }

        if (0 == _.size(_info.handCards)) {
            return;
        }

        if (null == this.outCardAll) {
            this.outCardAll = [];
        }
        var _seatIdx = _info.seatIdx;
        var dre = this.getDrection(_seatIdx);
        var _cardsInfo = PkCardTool.getCardInfos(_info.handCards);
        _cardsInfo = _.sortBy(_cardsInfo, function(_cardInfo) {
            return -_cardInfo.value * dre;
        });
        var offsetX = this.posOutEnd[_seatIdx].getContentSize().width * 0.5 * dre;
        _.each(_cardsInfo, function(_cardInfo, idx) {
            var ctr = UtilGameObject.getCtrByPrefabs(this.prefabShowOutCard, this.posOutEnd[_seatIdx]);
            this.outCardAll.push(ctr);
            ctr.refreshUI(_cardInfo);
            ctr.setActiveLandlord(false);
            ctr.setOpacity(0);
            ctr.setScale(this.getOutCardScale() + 0.1);
            ctr.setLocalZOrder(idx * dre + (idx <= 9 ? 0 : 100));
            ctr.setPositionX(offsetX * -1);
            ctr.setPositionY(5);
            var _t = idx * 0.1;
            var moveY = idx <= 9 ? 0 : -50;
            idx = idx <= 9 ? idx : idx - 10;
            var actAll = cc.spawn([
                cc.moveTo(_t, cc.v2(idx * 39 * dre - offsetX, moveY)),
                cc.scaleTo(_t, this.getOutCardScale()),
                cc.fadeIn(_t)
            ]);
            actAll.easing(cc.easeElasticInOut(3));
            ctr.doAction(actAll);
        }.bind(this));
    },

    /***其他家出牌表现 */
    actOtherOutCard(jData) {
        this.cleanOutCardAll();

        var _seatIdx = jData.seatIdx;
        var _cardsInfo = PkCardTool.getCardInfos(jData.cardIds);
        jData.cardsInfo = _cardsInfo;
        jData.sex = window.g_room.getSex(_seatIdx);
        var cardCnt = _.size(_cardsInfo);
        var beginworldPos = this.posHeadList[_seatIdx].convertToWorldSpaceAR(cc.v2(0, 0));
        var cardBeginPos = this.posOutEnd[_seatIdx].convertToNodeSpaceAR(beginworldPos);
        var d = this.getOtherD(_seatIdx);
        var isLandlord = false;
        if (window.g_room) {
            isLandlord = window.g_room.isLandlordSeatIdx(_seatIdx);
        }
        _cardsInfo = _.sortBy(_cardsInfo, function(_cardInfo) {
            return -_cardInfo.value * d;
        });
        var landlordIdx = _seatIdx == 1 ? 0 : (cardCnt - 1);
        var isBaset = this.isBastCard(_cardsInfo);
        var lastX = -1000;
        _.each(_cardsInfo, function(_cardInfo, _idx) {
            var ctr = UtilGameObject.getCtrByPrefabs(this.prefabShowOutCard, this.posOutEnd[_seatIdx]);
            ctr.setPosition(cardBeginPos);
            ctr.setLocalZOrder((-_idx * d));
            ctr.setOpacity(0.5);
            ctr.setScale(0.4);
            ctr.refreshUI(_cardInfo);

            ctr.setActiveLandlord(isLandlord && landlordIdx == _idx);

            var _fristX = this.getOtherOutPosX(_seatIdx, this.posOutEnd[_seatIdx], _idx);
            lastX = lastX < _fristX ? _fristX : lastX;

            var _t = this.getOutActTime();
            var act = cc.spawn([
                cc.moveTo(_t, cc.v2(_fristX, 0)),
                cc.scaleTo(_t, this.getOutCardScale()),
                cc.fadeIn(_t)
            ])
            var _delayTime = 0.04;
            var arry = [
                cc.delayTime(_idx * _delayTime),
                act,
                cc.delayTime((cardCnt - _idx + 1) * _delayTime)

            ];
            if (isBaset) {
                arry.push(this.doBastAct(ctr, _seatIdx, _idx));
            }
            var actAll = cc.sequence(arry);
            actAll.easing(cc.easeElasticOut(4));
            ctr.actOutCard(actAll);
            this.addOutCardAll([ctr]);
        }.bind(this));
        jData.lastX = lastX;
        this.playTypeAnim(jData);
    },

    getFristPosX(_cardSize) {
        if (1 == _cardSize) {
            return 0;
        }
        var x = -(_cardSize - 1) * this.getScapeX() * 0.5;
        return x;
    },

    /***自己出牌*/
    actOutCtrList(_ctrList) {
        this.cleanOutCardAll();
        this.addOutCardAll(_ctrList);
        var cardSize = _.size(_ctrList);
        var fristX = this.getFristPosX(cardSize);
        var _outCardsInfo = _.map(_ctrList, function(_ctr) {
            return _ctr.getCardId();
        });
        var _outCardsInfoSound = _.map(_ctrList, function(_ctr) {
            return _ctr.getCardInfo();
        });
        _outCardsInfo = _.compact(_outCardsInfo);
        var outInfos = {
            type: FindCardGroupType.getType(_outCardsInfoSound),
            cardIds: _outCardsInfo,
            cardsInfo: _outCardsInfoSound
        }
        if (!!window.g_room) {
            var selfSeatIdx = window.g_room.getSelfSeatIdx();
            outInfos.seatIdx = selfSeatIdx;
            outInfos.isFristOutCard = window.g_room.isResetOutCard();
            outInfos.sex = window.g_room.getSex(selfSeatIdx);
            window.g_room.outCardAct(outInfos);
        }
        var isBaset = this.isBastCard(_outCardsInfoSound);

        var lastX = this.playCardAnim(_ctrList, isBaset, outInfos);
        outInfos.lastX = lastX;
        this.playTypeAnim(outInfos);
    },

    playCardAnim(_ctrList, isBaset, outInfos) {
        isBaset = null == isBaset ? false : isBaset;
        var lastX = -1000;
        var cardSize = _.size(_ctrList);
        var fristX = this.getFristPosX(cardSize);
        var worldPos = this.posOutEnd[0].convertToWorldSpaceAR(cc.v2(0, 0));
        _.each(_ctrList, function(ctr, _idx) {
            ctr.setLocalZOrder(1000 + _idx);
            var time = this.getOutActTime();
            var _pos = ctr.node.parent.convertToNodeSpaceAR(worldPos);
            _pos.x = _pos.x + fristX + _idx * this.getScapeX();
            lastX = lastX < _pos.x ? _pos.x : lastX;
            var act1 = cc.spawn([cc.moveTo(time, _pos),
                cc.scaleTo(time, this.getOutCardScale())
            ]);
            var _delayTime = 0.05;
            var arry = [
                cc.delayTime(_idx * _delayTime),
                act1
            ];
            if (isBaset && outInfos) {
                arry.push(this.doBastAct(ctr, outInfos.seatIdx, _idx));
            }
            var actAll = cc.sequence(arry);
            actAll.easing(cc.easeElasticOut(time * 8));
            ctr.doAction(actAll);
        }.bind(this));

        this.showSelfCardBankerTag(_ctrList);
        return lastX;
    },
    /***自己出的牌显示庄标签 */
    showSelfCardBankerTag(_ctrList) {
        var size = _.size(_ctrList);
        if (window.g_room) {
            var selfSeatIdx = window.g_room.getSelfSeatIdx();
            var isLandlord = window.g_room.isLandlordSeatIdx(selfSeatIdx);
            _ctrList[size - 1].setActiveLandlord(isLandlord);
        }
    },
    /***每张牌之间的间距*/
    getScapeX() {
        return 45;
    },

    /**获取出牌的缩放*/
    getOutCardScale() {
        return 0.7;
    },

    /***预设的尺寸 */
    _getPrefabSize() {
        return new cc.size(this.prefabShowOutCard.data.width, this.prefabShowOutCard.data.height)
    },

    getDrection(_seatIdx) {
        if (0 == _seatIdx || 2 == _seatIdx) {
            return 1;
        }
        return -1;
    },
    /**播放出牌特效 */
    playTypeAnim(_info) {
        var type = _info.type;
        if (EumPkGroup.STRAIGHT == type || EumPkGroup.EVENPAIRS == type || EumPkGroup.THREEONE == type || EumPkGroup.THREEPAIRS == type) {
            this.playGuangEffectAnim(_info);
        } else if (EumPkGroup.BOMB == type) {
            this.playBombAnim(_info)
        } else if (EumPkGroup.BOMBKING == type) {
            this.playBombAnim(_info)
        } else if (EumPkGroup.AIRCRAFT == type) {
            UtilGameObject.createAddparentByPrefabs(this.prefabFeiJi, this.node);
            PkSound.outFeiJiAnim();
        }
    },
    playBombAnim(_info) {
        var winSize = cc.winSize;
        var seatIdx = _info.seatIdx;
        var sprite = UtilGameObject.getCtrByPrefabs(this.prefabSprite, this.nodeScene, "BaseSprite", 101);
        var spriteFrame = this.spriteAtlasBomb.getSpriteFrame('zhadan');
        sprite.setSpriteFrame(spriteFrame);
        sprite.setScale(0.6);
        var rot = this.getDrection(seatIdx);
        if (rot == 1) {
            sprite.setRotation(-80)
        } else {
            sprite.setRotation(80)
        }
        var beginworldPos = this.posHeadList[seatIdx].convertToWorldSpaceAR(cc.v2(0, 0));
        var beginPos = this.node.convertToNodeSpaceAR(beginworldPos);
        sprite.setPosition(beginPos);
        var bezier = [
            beginPos,
            cc.v2(0 - rot * winSize.width * .25, winSize.height * 0.5),
            cc.v2(0, winSize.height * 0.2)
        ]
        var time = 0.5;
        var bezierTo = cc.bezierTo(time, bezier);
        var rotateBy = cc.rotateBy(time, 100 * rot);
        var endCb = cc.callFunc(function() {
            sprite.node.destroy();
            PkSound.outBombAnim();
            var spriteFrameAnim = UtilGameObject.getCtrByPrefabs(this.prefabCardTypeAnim, this.node, "BaseSpriteFrameAnim", 100);
            spriteFrameAnim.setScale(1.5);
            var animState = spriteFrameAnim.playBySpriteFrameNameArea('zd', 1, 22, this.spriteAtlasBomb.getSpriteFrames());
            animState.speed = 1;
        }.bind(this));
        var actScale = cc.scaleTo(time, 0.8);
        var boomSpa = cc.spawn([bezierTo, rotateBy, actScale]);
        sprite.doAction(cc.sequence([boomSpa, endCb]));


        var winScaleBig = cc.scaleTo(0.35, 1.2);
        winScaleBig.easing(cc.easeSineOut());
        var winScaleSmall = cc.scaleTo(0.15, 1);
        winScaleSmall.easing(cc.easeSineIn());
        var act = cc.sequence([winScaleBig, winScaleSmall])
        this.nodeScene.runAction(act);

    },
    /***发光特效 */
    playGuangEffectAnim(_info) {
        _info.lastX = null == _info.lastX ? 0 : _info.lastX - 200;
        var seatIdx = _info.seatIdx;
        var type = _info.type;
        var spriteFrameAnim = UtilGameObject.getCtrByPrefabs(this.prefabCardTypeAnim, this.posOutEnd[seatIdx], "BaseSpriteFrameAnim", 100);
        spriteFrameAnim.setScale(1.9);
        // spriteFrameAnim.setPositionX(-120);
        spriteFrameAnim.setPositionX(_info.lastX);
        var sprite = UtilGameObject.getCtrByPrefabs(this.prefabSprite, this.posOutEnd[seatIdx], "BaseSprite", 101);
        sprite.setScale(0.9);
        // sprite.setPositionX(-50);
        sprite.setPositionX(_info.lastX + 70);
        sprite.setOpacity(0);
        var worldSpriteName = 'btn_shunzi';
        if (EumPkGroup.STRAIGHT == type) {
            worldSpriteName = 'btn_shunzi';
        } else if (EumPkGroup.EVENPAIRS == type) {
            worldSpriteName = 'btn_liandui';
        } else if (EumPkGroup.THREEONE == type) {
            worldSpriteName = 'btn_sdy';
        } else if (EumPkGroup.THREEPAIRS == type) {
            worldSpriteName = 'btn_sdyd';
        }
        var spriteFrame = this.spriteAtlasPkType.getSpriteFrame(worldSpriteName);
        sprite.setSpriteFrame(spriteFrame);
        var t = 0.2;
        var acts = [
            cc.spawn([cc.moveBy(t, cc.v2(60, 0)), cc.fadeIn(t), cc.scaleTo(t, 1)]),
            cc.spawn([cc.moveBy(t, cc.v2(15, 0)), cc.delayTime(t)]),
            cc.spawn([cc.moveBy(t, cc.v2(5, 0)), cc.fadeTo(t, 200)]),
            cc.spawn([cc.moveBy(t, cc.v2(5, 0)), cc.fadeOut(t)]),
            cc.callFunc(function() {
                if (!sprite && !sprite.node) {
                    sprite.node.destroy();
                }
            })
        ];
        PkSound.outStraightAnim();
        sprite.doAction(cc.sequence(acts));
        spriteFrameAnim.play();
    },
    /***可能最大的牌动画 */
    doBastAct(_ctr, _seatIdx, _idx) {
        var act = cc.spawn(
            [
                cc.rotateTo(0.05, -10),
                cc.scaleTo(0.05, 0.7),
            ]
        );
        return cc.sequence([cc.callFunc(function() {
            _ctr.node.setAnchorPoint(0, 0);
            var sprite = UtilGameObject.getCtrByPrefabs(this.prefabSprite, this.nodeBg, "BaseSprite", 0);
            var pos = this.posOutEnd[_seatIdx].position;
            sprite.setPositionX(pos.x - 10);
            sprite.setPositionY(pos.y + 10);
            var spriteFrame = this.spriteAtlasBastCardEffect.getSpriteFrame('huo');
            sprite.setSpriteFrame(spriteFrame);
            var arr = [
                cc.scaleTo(0.05, 1.3),
                cc.scaleTo(0.05, 0.8),
                cc.delayTime(0.05),
                cc.fadeOut(0.4)
            ];
            sprite.doAction(cc.sequence(arr));
            if (0 == _idx) {
                PkSound.getOtherCardAnim();
            }
        }.bind(this)), act, cc.rotateTo(0, 0), cc.scaleTo(0, 0.65)]);
    },

    isBastCard(cardsInfo) {
        var cnt = _.size(cardsInfo);
        if (1 == cnt) {
            return cardsInfo[0].value == 16 || cardsInfo[0].cardType == 5;
        } else if (2 == cnt) {
            return cardsInfo[0].value == 16 && cardsInfo[1].value == 16;
        }
        return false;
    }
});